﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Collections;
using System.Drawing.Drawing2D;
using Microsoft.Win32;


namespace FileOperationWinform
{

    public partial class FormMain : Form
    {
        private static readonly string ExceptLotion=ConfigurationManager.AppSettings["Except"];

        #region  增加线程终止操作 2012-07-08 
        private ManualResetEvent manualResetEvent;
        private AutoResetEvent auto;
        private bool suspend;
        private AsyncOperation asyncoperation;
        public delegate void InvokeDelegate(string str);
        private InvokeDelegate invokeDelegate;
        const string str = "FileAutoCount";
        private bool formClosed;
        #endregion
        public class recordflag
        {
            public string location;
            public int pdf;
            public int zip;
            public int rar;
            public int microsoft2003;
            public int microsoft2007;
            public int wps;
            public int Rest;
            public int CountNum;
            public System.Data.DataTable recordList;
        };
        public FormMain()
        {
            InitializeComponent();
        #region  增加线程终止操作 2012-07-08
            manualResetEvent = new ManualResetEvent(false);
            auto = new AutoResetEvent(true);
            asyncoperation = AsyncOperationManager.CreateOperation(null);
            invokeDelegate = new InvokeDelegate(this.SafeInvoke);
            this.FormClosed += delegate
            {
                this.formClosed = true;
                this.auto.Close();
            };
        #endregion
        }

        //private Stopwatch sw = new Stopwatch();
        //public delegate void ParameterizedThreadStart(object obj);
        private delegate void FlushClient();// proxy

        private delegate void SetTextStr(string text);
        private delegate void SetTextint(int text);

        private delegate void SetCommonTextStr(int s, int str);
        public void SetComonText(int s, int str)
        {
            switch (s)
            {
                case 1:
                    if (this.label3.InvokeRequired)
                    {
                        SetCommonTextStr d = new SetCommonTextStr(SetComonText);
                        this.Invoke(d, new object[] { s, str });
                    }
                    else
                    {
                        this.label3.Text = Convert.ToString(str);
                    }
                    break;
                case 2:
                    if (this.label5.InvokeRequired)
                    {
                        SetCommonTextStr d = new SetCommonTextStr(SetComonText);
                        this.Invoke(d, new object[] { s, str });
                    }
                    else
                    {
                        this.label5.Text = Convert.ToString(str);
                    }
                    break;
                case 3:
                    if (this.label7.InvokeRequired)
                    {
                        SetCommonTextStr d = new SetCommonTextStr(SetComonText);
                        this.Invoke(d, new object[] { s, str });
                    }
                    else
                    {
                        this.label7.Text = Convert.ToString(str);
                    }
                    break;
            }
        }

        public delegate void listevent(object e, DrawItemEventArgs a);
        public event listevent Alarm;
        //private delegate void SetTextint1(int  text);
        //private delegate void SetTextint2(int  text);


        public void SetTextBox1(string str)
        {
            if (this.textBox1.InvokeRequired)
            {
                SetTextStr d = new SetTextStr(SetTextBox1);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                this.textBox1.Text = str;
            }
        }
        public void SetTextBox2(string str)
        {
            if (this.textBox2.InvokeRequired)
            {
                SetTextStr d = new SetTextStr(SetTextBox2);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                this.textBox2.Text = str;
            }
        }

        private string eventinformation;
        private string t
        {
            get { return eventinformation; }
            set
            {
                eventinformation = value;
                if (Alarm != null)
                {
                    Alarm(this, null);
                }
            }
        }
        public void SetTextBox3(string str)
        {
            if (this.listBox1.InvokeRequired)
            {
                SetTextStr d = new SetTextStr(SetTextBox3);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                this.listBox1.Items.Add(str);
                Alarm += new listevent(this.Ontestevent);
                //t = "gdsg";


            }
        }

        public void Ontestevent(object obj, DrawItemEventArgs e)
        {
            MessageBox.Show("testevent\r\n");
        }
        /*
        public void SetTextBox4(int str)
        {
            if (this.label3.InvokeRequired)
            {
                SetTextint d = new SetTextint(SetTextBox4);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                this.label3.Text = Convert.ToString(str);
            }
        }
        public void SetTextBox5(int str)
        {
            if (this.label5.InvokeRequired)
            {
                SetTextint d = new SetTextint(SetTextBox5);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                this.label5.Text = Convert.ToString(str);
            }
        }
        public void SetTextBox7(int str)
        {
            if (this.label7.InvokeRequired)
            {
                SetTextint d = new SetTextint(SetTextBox7);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                this.label7.Text = Convert.ToString(str);
            }
        }
        */
        public void SetDataGridView(string str)
        {
            if (this.dataGridView1.InvokeRequired)
            {
                SetTextStr d = new SetTextStr(SetDataGridView);
                this.Invoke(d, new object[] { str });
            }
            else
            {

                this.dataGridView1.DataSource = this.CreateDataSet();
                this.dataGridView1.DataMember = "Student";
            }
        }

        public void SetButton(string str)
        {
            if (this.button3.InvokeRequired)
            {
                SetTextStr d = new SetTextStr(SetButton);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                MessageBox.Show("程序共运行时间:" + timecount + "秒\r\n" + "pdf:"
    + x.pdf + " rar:" + x.rar + " zip:" + x.zip + "\r\n"+"Microsoft 2003:" + x.microsoft2003
    +" Microsoft 2007:"+x.microsoft2007+"\r\n"+str);
                this.button3.Enabled = true;
            }
        }

        //private void CrossThreadFlush()
        //{
        //    while (true)
        //    {
        //        Thread.Sleep(1000);
        //        record();
        //    }
        //}
        //private void record(object obj, DoWorkEventArgs e)
        ArrayList myList = new ArrayList();
        private void exceptfil()
        {
            string tempstr = Path.Combine(Application.StartupPath, ExceptLotion);
            if (File.Exists(tempstr))
            {
                string[] str = new string[2];
                string[] temp = new string[3];
                FileStream fs = new FileStream(tempstr, FileMode.Open, FileAccess.Read);
                StreamReader sw = new StreamReader(fs);
                
                string line = sw.ReadLine();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; line!=null; i++)
                {
                    temp=line.Split(',');
                    str[0]=temp[1];
                    str[1]=temp[2];
                    myList.Add(str[1]);
                    line = sw.ReadLine();
                }
                sw.Close();
                fs.Close();
            }
        }

        ArrayList my = new ArrayList();

        ArrayList FileEx = new ArrayList();
        private void excefiletype()
        {
            string tempstr = Path.Combine(Application.StartupPath, ExceptLotion);

            if (File.Exists(tempstr))
            {
                string[] str = new string[2];
                string[] temp = new string[3];
                //string[] temp1=new string[]
                FileStream fs = new FileStream(tempstr, FileMode.Open, FileAccess.Read);
                StreamReader sw = new StreamReader(fs);
                string line = sw.ReadLine();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; line != null; i++)
                {
                    temp = line.Split(',');
                    str[0] = temp[1];
                    str[1] = temp[2];
                    //ListViewItem item = new ListViewItem(str, 0);
                    //listView1.Items.Add(item);
                    my.Add(str[1]);
                    //str1.Split(",");
                    line = sw.ReadLine();
                }
                sw.Close();
                fs.Close();
            }

        }
        private int filetypesame(string str)
        {
            string tempstr = Path.Combine(Application.StartupPath, ExceptLotion);
            if (File.Exists(tempstr))
            {
                foreach (string s in my)
                {
                    if (string.Compare(str, s) == 0)
                    {
                        return 1;
                    }
                }
            }
            return 0;
        }
        private string kk()
        {
            string s = "";
            string s1 = "";
            string[] filetyepe=new string[2];
            for (int i = 0; i <dt.Rows.Count; i++)
            {
                if ((i+1)% 3 == 0){
                    s1 = "\r\n";
                }
                else
                    s1 = "";
                filetyepe = dt.Rows[i][1].ToString().Split('.');
                s += ( filetyepe[1]+ ":" + Convert.ToString(dt.Rows[i][2])+" "+s1);
            }
            return s;
        }
        private int timecount = 0;
        private void record(object str)
        {
            Stopwatch sw = new Stopwatch();
            recordflag t = (recordflag)str;
            #region  record file
            int i = 0;
            int pdf = 0, rar = 0, zip = 0, microsoft2003 = 0, microsoft2007 = 0, wps = 0;
            Queue<string> qu = new Queue<string>();
            #region
            //if (this.textBox1.InvokeRequired)
            //{
            //    FlushClient fc=new FlushClient(record);
            //    qu.Enqueue(textBox1.Text);
            //    this.Invoke(fc);
            //}
            #endregion

            //string str1 = (recordflag)str;

            string str1 = t.location;
            //qu.Enqueue(textBox1.Text);
            //SetTextBox1(str);
            qu.Enqueue(str1);
            excefiletype();
            CreateExceptFile();
            string currentPath = "";

            DirectoryInfo di = null;
            FileSystemInfo[] fi = null;
            FileSystemInfo[] dirs = null;

            try
            {
                sw.Start();
                while (qu.Count > 0)
                {
                    currentPath = qu.Dequeue();
                    di = new DirectoryInfo(currentPath);
                    //System.IO.FileInfo objFI = new System.IO.FileInfo(currentPath);

                    try
                    {
                        fi = di.GetFiles();
                        dirs = di.GetDirectories();
                        foreach (FileSystemInfo f in fi)
                        {
                            if (f.Extension == ".pdf" && t.pdf == 1)
                            {
                                //if (this.listBox1.InvokeRequired)
                                //{
                                //    FlushClient fc1 = new FlushClient(record);
                                //    listBox1.Items.Add(f.FullName);
                                //    this.Invoke(fc1);
                                //}
                                //listBox1.Items.Add(f.FullName);                     
                                pdf += 1;
                                //SetTextBox4(pdf);
                                SetComonText(1, pdf);
                                SetTextBox3(f.FullName);
                            }
                            if (f.Extension == ".rar" && t.rar == 1)
                            {
                                rar += 1;
                                //SetTextBox5(rar);
                                SetComonText(2, rar);
                                SetTextBox3(f.FullName);
                            }
                            if (f.Extension == ".zip" && t.zip == 1)
                            {
                                zip += 1;
                                //SetTextBox7(zip);
                                SetComonText(3, zip);
                                SetTextBox3(f.FullName);
                            }
                            if (f.Extension == ".ppt" | f.Extension == ".xls" | f.Extension == ".doc" && t.microsoft2003 == 1)
                            {
                                microsoft2003 += 1;
                                SetTextBox3(f.FullName);
                            }
                            if (f.Extension == ".pptx" | f.Extension == ".xlsx" | f.Extension == ".docx" && t.microsoft2007 == 1)
                            {
                                microsoft2007 += 1;
                                SetTextBox3(f.FullName);
                            }

                            if (filetypesame(f.Extension) == 1)
                            {
                                EnumTable(f.Extension);
                                SetTextBox3(f.FullName);
                            }

                            i += 1;
                            SetTextBox2("" + i.ToString());
                        }

                        foreach (FileSystemInfo d in dirs)
                        {
                            qu.Enqueue(d.FullName);
                        }
                    }
                    catch (UnauthorizedAccessException ce)
                    {
                        FileLog.writelog("Log.Config", ce.Message.ToString());
                        continue;
                    }
                    catch (Exception ce1)
                    {
                        if (Marshal.GetLastWin32Error() == 3)
                        {
                            continue;
                        }
                        else
                        {
                            MessageBox.Show("路径不正确或不存在，ErrorMessage:" + ce1.Message.ToString() + "ErrorNum:" + Marshal.GetLastWin32Error(), "信息提示");
                            return;
                        }
                    }
                }

                CreateDataSet();
                #region unuse
#if A
            this.textBox1.Text = i.ToString();
            if (this.textBox2.InvokeRequired)
            {
                FlushClient fc3 = new FlushClient(record);
                this.textBox2.Text = i.ToString();
                this.Invoke(fc3);
            }
            this.textBox2.Text = i.ToString();
#endif
                #endregion
                sw.Stop();
                timecount = sw.Elapsed.Seconds;
                TypeCountNum(pdf, rar, zip, microsoft2003, microsoft2007, wps, i);

                SetButton(kk());
                SetDataGridView("d");
            }catch(ThreadAbortException e)
            {
                MessageBox.Show("dfdsgd");
            }
            #endregion

        }
        private void TypeCountNum(int pdf, int rar, int zip, int microsoft2003, int microsoft2007, int wps,int count)
        {
            x.pdf = pdf;
            x.rar = rar;
            x.zip = zip;
            x.microsoft2003 = microsoft2003;
            x.microsoft2007 = microsoft2007;
            x.wps = wps;
            x.Rest = count - pdf - rar - zip - microsoft2003 - microsoft2007 - wps;
            x.CountNum = count;
            x.recordList = dt;
        }
        public bool ExportDataSetGridview(DataGridView gridview, bool isShowExcel)
        {
            if (gridview.Rows.Count == 0)
            {
                return false;
            }
            try
            {
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                excel.Application.Workbooks.Add(true);
                excel.Visible = isShowExcel;

                for (int i = 0; i < gridview.ColumnCount; i++)
                {
                    excel.Cells[1, i + 1] = gridview.Columns[i].HeaderText;
                }

                for (int i = 0; i <=gridview.RowCount - 1; i++)
                {
                    for (int j = 0; j < gridview.ColumnCount; j++)
                    {
                        if (gridview[j, i].ValueType == typeof(string))
                        {
                            excel.Cells[i + 2, j + 1] = "" + gridview[j, i].Value.ToString();
                        }
                        else
                        {
                            excel.Cells[i + 2, j + 1] = gridview[j, i].Value.ToString();
                        }
                    }
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
        System.Data.DataTable dt = new DataTable("Table_AX");
        private void CreateExceptFile()
        {
            dt.Clear();
            dt.Columns.Clear();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows.RemoveAt(i);
                //dt.AcceptChanges();
            }

            dt.Columns.Add("Num", System.Type.GetType("System.Int32"));
            dt.Columns.Add("FileExtense", System.Type.GetType("System.String"));
            dt.Columns.Add("FileNum", System.Type.GetType("System.Int32"));
            DataRow dr;
            for (int i = 0; i < my.Count; i++)
            {
                dr = dt.NewRow();
                dr["Num"] = i;
                dr["FileExtense"] = my[i].ToString();
                dr["FileNum"] = 0;
                dt.Rows.Add(dr);
            }
        }
        private void EnumTable(string x)
        {
            int olddata;
            int newdata;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (string.Compare(x, dt.Rows[i][1].ToString()) == 0)
                {
                    olddata = Convert.ToInt32(dt.Rows[i][2].ToString());
                    newdata = olddata + 1;
                    dt.Rows[i][2] = newdata;
                }
            }
        }
        System.Data.DataTable stuTable;
        private DataSet CreateDataSet()
        {
            DataSet strds = new DataSet();
            stuTable = new DataTable("Student");
            DataColumn stuColumn = new DataColumn();
            //构建表结构，添加列
            stuColumn.DataType = System.Type.GetType("System.Int32");
            stuColumn.ColumnName = "文件编号";
            stuColumn.AllowDBNull = false;
            //将列添加到Table中
            stuTable.Columns.Add(stuColumn);
            //往表中添加列
            stuTable.Columns.Add("文件名", typeof(string));
            stuTable.Columns.Add("其他", typeof(int));
            DataRow stuRow;
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                stuRow = stuTable.NewRow();
                stuRow["文件编号"] = i;
                stuRow["文件名"] = listBox1.Items[i].ToString();
                stuRow["其他"] = 25;

                stuTable.Rows.Add(stuRow);
            }
            //DataRow stuRow = stuTable.NewRow();
            //stuRow["stuNo"] = id;
            //stuRow["stuName"] = str;
            //stuRow["stuAge"] = 25;
            ////把数据添加到表结构中
            //stuTable.Rows.Add(stuRow);
            //stuRow = stuTable.NewRow();
            //stuRow["stuNo"] = 101;
            //stuRow["stuName"] = "w1";
            //stuRow["stuAge"] = 25;
            //stuTable.Rows.Add(stuRow);
            //将表结构添加到DataSet中
            strds.Tables.Add(stuTable);
            return strds;


        }
        private static BackgroundWorker bw = new BackgroundWorker();
        //Thread tthread;
        private void button1_Click(object sender, EventArgs e)
        {
            x.location = textBox1.Text;
            x.pdf = Convert.ToInt32(checkBox1.Checked);
            x.rar = Convert.ToInt32(checkBox2.Checked);
            x.zip = Convert.ToInt32(checkBox3.Checked);
            x.microsoft2003 = Convert.ToInt32(checkBox4.Checked);
            x.microsoft2007 = Convert.ToInt32(checkBox5.Checked);
            x.wps = Convert.ToInt32(checkBox7.Checked);

            string str = "0";
            this.textBox2.Text = str;
            this.label3.Text = str;
            this.label5.Text = str;
            this.label7.Text = str;
            this.listBox1.Items.Clear();
            my.Clear();
            stuTable = null;
            #region unuse
            //Alarm += new listevent(Ontestevent);
            //test t1 = new test();
            //t1.Altem+=new test.lisete(Ontestevent);
            //t1.testmes = "dd";
            //record(x);
            #endregion
            FileLog.writelog("Log.Config",textBox1.Text.ToString());
            Thread tthread = new Thread(new ParameterizedThreadStart(record));
            tthread.IsBackground = true;  // Main Thread exit,Child  Thread without exit
            tthread.Start(x);
            #region   改变子线程无法停止 2012-07-08
            //ThreadPool.QueueUserWorkItem(delegate { SafeInvoke(); });
            #endregion
        }
        #region 增加线程停止 2012-07--08
        private void SafeInvoke(string s)
        {
            while (true)
            {
                if (formClosed) { return; }
                Thread.Sleep(200);
                if (suspend)
                {
                    this.auto.WaitOne();
                }
            }
        }

        private void SafeInvoke()
        {
            while (true)
            {
                if (formClosed)
                {
                    return;
                }
                Thread.Sleep(200);
                if (suspend)
                {
                   
                    manualResetEvent.WaitOne();
                    //asyncoperation.Post(delegate { this.txtMessageBox.AppendText(str); },str);
                    asyncoperation.Post(delegate { record(x); },str);
                }
                record(x);
            }
        }
        #endregion
        private void button2_Click(object sender, EventArgs e)
        {
            //this.suspend = true;
            //manualResetEvent.Reset();

            //tthread.Suspend();
            
            SetControlNUll();
        }

        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        /// <summary>
        /// 释放内存
        /// </summary>
        public static void ClearMemory()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
               SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
        }

        public int ExistsRegedit()
        {
            int ifused = 0;
            RegistryKey rk = Registry.LocalMachine;
            //查询Office2003
            RegistryKey f03 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\11.0\Excel\InstallRoot\");
            //查询Office2007
            RegistryKey f07 = rk.OpenSubKey(@"SOFTWARE\Microsoft\Office\12.0\Excel\InstallRoot\");
            ////查询wps
            //RegistryKey wps = rk.OpenSubKey(@"SOFTWARE\Kingsoft\Office\6.0\common\");
            //检查本机是否安装Office2003
            if (f03 != null)
            {
                //string file03 = f03.GetValue("Path").ToString();
                //if (File.Exists(file03 + "Excel.exe")) ifused += 1;
                ifused = 1; 
            }
            //检查本机是否安装Office2007
            if (f07 != null)
            {
                //string file07 = akey.GetValue("Path").ToString();
                //if (File.Exists(file07 + "Excel.exe")) ifused += 2;
                ifused = 2; 
            }

            //检查本机是否安装wps
            //if (wps != null)
            //{
            //    //string filewps = akeytwo.GetValue("InstallRoot").ToString();
            //    //if (File.Exists(filewps + @"\office6\et.exe")) ifused += 4;
            //    ifused = 3; 
            //}
            return ifused;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Control.CheckForIllegalCrossThreadCalls = false;
            this.btnMap.Focus();
            button1.Enabled = false;
            button3.Enabled = false;
            button2.Enabled = true;
            btnMap.Enabled = false;
            textBox1.Enabled = false;
            this.timer1.Enabled = true;

            this.tabControl2.Visible = false;
            //this.tabControl2.TabPages[1].Hide();

            //foreach (TabPage tg in this.tabControl2.TabPages)
            //{
            //    if (tg.Text=="1")
            //    {
            //        this.tabControl2.TabPages.Remove((tg));
            //        break;
            //    }
            //}

            FileOpera ft = new FileOpera();
            string st = ft.SkinLoad();
            //MessageBox.Show(st);
            if (!(string.Equals(st, "Error")))
            {
                string  xx=System.IO.Path.Combine(Application.StartupPath, st);
                skinEngine1.SkinFile = xx;
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            int i = ExistsRegedit();
            i = 2;
            if (i==1)
            {
                OpenFileDialog t = new OpenFileDialog();
                t.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                t.Filter = "Excel2003|*.xls";
                t.Title = "导入Excel2003";
                t.RestoreDirectory = true;

                DialogResult dr = t.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    string cs = OperaExcel.ExportTable2ExcelFile(stuTable, t.FileName, (DateTime.Now.Day.ToString() + DateTime.Now.Minute.ToString()));
                    MessageBox.Show(cs);
                }
            }
            if(i==2)
            {
            Thread t = new Thread(new ParameterizedThreadStart(exportexcel));
            t.Start(this.dataGridView1);
            }
        }
        recordflag x = new recordflag();
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.tabControl2.Visible = false;
            try
            {
                Process.Start(listBox1.SelectedItem.ToString(), "open");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("请安装该格式的阅读器！");
            }

            //MessageBox.Show(listBox1.SelectedItem.ToString());
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            button1.Enabled = true;
            button2.Enabled = true;
            btnMap.Enabled = true;
            //button3.Enabled = true;
            //textBox1.ReadOnly = true;
        }
        private void SetControlNUll()
        {
            listBox1.Items.Clear();
            this.radioButton1.Checked = false;
            this.radioButton2.Checked = false;
            this.btnMap.Enabled = false;
            textBox1.ReadOnly = true;
            textBox1.Text = String.Empty;
            button1.Enabled = false;
            button3.Enabled = false;
            button2.Enabled = false;
            string str = String.Empty;
            this.textBox2.Text = str;
            this.label3.Text = str;
            this.label5.Text = str;
            this.label7.Text = str;
            this.checkBox1.Checked = false;
            this.checkBox2.Checked = false;
            this.checkBox3.Checked = false;
            this.checkBox4.Checked = false;
            this.checkBox5.Checked = false;
            this.checkBox7.Checked = false;
            this.txtKeyWords.Text = String.Empty;
            this.dataGridView1.DataSource = null;
        }
        #region unuse
        //private delegate void Gridvie(DataGridView t);

        //private void Gridbv(DataGridView t)
        //{
        //    if (this.dataGridView1.InvokeRequired)
        //    {
        //        Gridvie d = new Gridvie(Gridbv);
        //        this.Invoke(d, new object[] { t });
        //    }
        //    else
        //    {
        //        this.dataGridView1 = t;
        //    }
        //}
        #endregion
        private void exportexcel(object obj)
        {
            DataGridView t = (DataGridView)obj;
            bool flag = ExportDataSetGridview(t, true);
            if (flag == false)
            {
                MessageBox.Show("请安装Microsoft 2007或者更高版本！");
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            //string path = Path.Combine(Application.StartupPath, @"Skin");
            //SaveDataTableToExcel(stuTable,path);

            printAll(stuTable);
            
            //SaveAs();
            //SaveFileDialog saveFileDialog = new SaveFileDialog();
            //saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            //saveFileDialog.FilterIndex = 0;
            //saveFileDialog.RestoreDirectory = true;
            //saveFileDialog.CreatePrompt = true;
            //saveFileDialog.Title = "Export Excel File To";
            //saveFileDialog.ShowDialog();


            
            //MessageBox.Show(this.Bounds.Width.ToString());
            //exceptfil();
            //FileOperation.FileObj fs = new FileOperation.FileObj();
            //fs.testhelp();
            //System.Diagnostics.Process p = new System.Diagnostics.Process();
            //p.StartInfo.FileName = "FileOpeationHelp.chm";
            //p.Start();

            //System.Diagnostics.Process.Start("FileOpeationHelp.chm");
        }
        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (this.txtKeyWords.Text != "")
            {
                try
                {
                    if (this.listBox1.Items[e.Index].ToString().IndexOf(this.txtKeyWords.Text) > -1)
                    {
                        Brush br;
                        int r = 0;
                        //Math.DivRem(e.Index,2,out r);
                        if (r == 0)
                        {
                            br = Brushes.Red;
                        }
                        else
                        {
                            br = Brushes.Blue;
                        }
                        e.DrawBackground();
                        if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                        {
                            e.DrawFocusRectangle();
                        }
                        Brush b = Brushes.Black;
                        e.Graphics.FillRectangle(br, e.Bounds);
                        e.Graphics.DrawString(this.listBox1.Items[e.Index].ToString(), this.listBox1.Font, b, e.Bounds);
                    }
                    else
                    {
                        Brush br;
                        br = Brushes.White;
                        Brush b = Brushes.Black;
                        e.Graphics.FillRectangle(br, e.Bounds);
                        e.Graphics.DrawString(this.listBox1.Items[e.Index].ToString(), this.listBox1.Font, b, e.Bounds);
                    }
                }
                catch (Exception ce)
                {
                    return;
                }
            }
            else
            {
                try
                {
                    Brush br;
                    br = Brushes.White;
                    Brush b = Brushes.Black;
                    e.Graphics.FillRectangle(br, e.Bounds);
                    e.Graphics.DrawString(this.listBox1.Items[e.Index].ToString(), this.listBox1.Font, b, e.Bounds);
                }
                catch (Exception ce)
                {
                    return;
                }
            }
        }
        public listevent Form1_onevent { get; set; }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            File.Delete(Application.StartupPath + @"\\" + ExceptLotion);
            Application.Exit();
        }
        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (txtKeyWords.Text != "")
            {

                if (this.dataGridView1.Rows.Count != 0)
                {
                    for (int i = 0; i < this.dataGridView1.Rows.Count; )
                    {
                        //this.gvPersonnel.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.AliceBlue;
                        //i += 2;
                        //MessageBox.Show(" " + dataGridView1.Rows[i].Cells[1].Value.ToString());
                        if (dataGridView1.Rows[i].Cells[1].Value.ToString().IndexOf(txtKeyWords.Text.ToString()) > -1)
                        {
                            this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.Red;
                        }
                        //if (this.dataGridView1.Rows[i].Cells["列字段名"].Value == "某某值")
                        //{
                        //    this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.White;
                        //}
                        //else if (this.dataGridView1.Rows[i].Cells["列字段名"].Value == "某某值")
                        //{
                        //    this.dataGridView1.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.Azure;
                        //}

                        i += 1;
                    }
                }
            }
        }
        bool bchecked;
        bool bchecked1;
        private void radioButton1_MouseDown(object sender, MouseEventArgs e)
        {
            bchecked = this.radioButton1.Checked;
        }
        private void radioButton1_MouseUp(object sender, MouseEventArgs e)
        {
            if (bchecked)
            {
                this.radioButton1.Checked = false;
                btnSelectLocation.Enabled = true;
                textBox1.Enabled = false;
            }
        }
        private void radioButton1_Click(object sender, EventArgs e)
        {
            if (this.radioButton1.Checked)
            {
                btnSelectLocation.Enabled = false;
                textBox1.Text = "";
                textBox1.Enabled = true;
            }
        }
        private void btnSelectLocation_Click(object sender, EventArgs e)
        {
            DialogResult dr = folderBrowserDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog1.SelectedPath.ToString();
            }
        }
        private void button5_Click(object sender, EventArgs e)
        {
            if (this.listBox1.Items.Count==0)
            {
                MessageBox.Show("没有你需要分析的统计结果！","信息提示");
                return;
            }else
            {
                if (x.recordList != null)
                {
                    FrmMap fm = new FrmMap(x);
                    fm.ShowDialog();
                }
            }
        }
        private void listBox1_MouseMove(object sender, MouseEventArgs e)
        {
            #region    listview
            #if A
            ListView _ListView = (ListView)sender;
            ListViewItem _Item = _ListView.GetItemAt(e.X, e.Y);
            if (_Item==null)
            {
                return;
            }
            string _ShowText = "";
            for (int i = 0; i != _ListView.Columns.Count;i++ )
            {
                _ShowText+=listBox1.Colum
            }
            #endif
            #endregion

            ListBox _ListBox = (ListBox)sender;
            for (int i = 0; i != _ListBox.Items.Count;i++ )
            {
                Rectangle _Rect = _ListBox.GetItemRectangle(i);
                if (_Rect.Contains(e.X,e.Y))
                {
                    toolTip1.Show(_ListBox.Items[i].ToString(), _ListBox, e.X + 10, e.Y, 3000);
                }
            }
        }
        private void radioButton1_TextChanged(object sender, EventArgs e)
        {
            if (radioButton1.Checked)
            {
                textBox1.Enabled = true;
            }
            else
            {
                textBox1.Enabled = false;
            }
        }
        private void button5_Click_1(object sender, EventArgs e)
        {
            FrmExcept frm = new FrmExcept();
            frm.ShowDialog();
        }
        private void radioButton2_MouseDown(object sender, MouseEventArgs e)
        {
            bchecked1 = this.radioButton2.Checked;
        }
        private void radioButton2_MouseUp(object sender, MouseEventArgs e)
        {
            if (bchecked1)
            {
                this.radioButton2.Checked = false;
                checkBox1.Checked = false;
                checkBox2.Checked = false;
                checkBox3.Checked = false;
                checkBox4.Checked = false;
                checkBox5.Checked = false;
                checkBox7.Checked = false;

            }
        }
        private void radioButton2_Click(object sender, EventArgs e)
        {
            if (this.radioButton2.Checked)
            {
                checkBox1.Checked = true;
                checkBox2.Checked = true;
                checkBox3.Checked = true;
                checkBox4.Checked = true;
                checkBox5.Checked = true;
                checkBox7.Checked = true;
            }
        }
        [DllImport("User32.dll")]
        private static extern IntPtr GetWindowDC(IntPtr hWnd);
        [DllImport("User32.dll")]
        private static extern int ReleaseDC(IntPtr hWnd, IntPtr hdc);
        [DllImport("Kernel32.dll")]
        private static extern int GetLastError();
        Rectangle m_rect = new Rectangle(460, 4, 16, 16);
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            switch (m.Msg)
            {
                case 0x86:
                case 0x85:
                    {
                        IntPtr hDC = GetWindowDC(m.HWnd);
                        Graphics gs = Graphics.FromHdc(hDC);
                        gs.FillRectangle(new LinearGradientBrush(m_rect, Color.Pink, Color.Purple, LinearGradientMode.BackwardDiagonal),
                            m_rect);
                        StringFormat strFmt = new StringFormat();
                        strFmt.Alignment = StringAlignment.Center;
                        strFmt.LineAlignment = StringAlignment.Center;
                        gs.DrawString("e", this.Font, Brushes.BlanchedAlmond, m_rect, strFmt);
                        gs.Dispose();
                        ReleaseDC(m.HWnd, hDC);
                        break;
                    }
                case 0xA1:
                    {
                        Point mousePoint = new Point((int)m.LParam);
                        mousePoint.Offset(-this.Left, -this.Top);
                        if (m_rect.Contains(mousePoint))
                        {
                            MessageBox.Show("Hello");
                        }
                        break;
                    }
            }
        }
        private void FormMain_SizeChanged(object sender, EventArgs e)
        {
            m_rect.X = this.Bounds.Width - 42 - this.MinimumSize.Width * 3;
            m_rect.Y = 4;
            m_rect.Width = m_rect.Height = 16;
        }
        private void button6_Click(object sender, EventArgs e)
        {
            if (this.tabControl2.Visible==true)
            {
                this.tabControl2.Visible = false;
            }
            else
            {
                this.tabControl2.Visible = true;
            }
            
        }
        private void btnMap_Click(object sender, EventArgs e)
        {
            if (this.listBox1.Items.Count == 0)
            {
                MessageBox.Show("没有你需要分析的统计结果！", "信息提示");
                return;
            }
            else
            {
                if (x.recordList != null)
                {
                    FrmMap fm = new FrmMap(x);
                    fm.ShowDialog();
                }
            }
        }
        private static readonly string exceptlocation = ConfigurationManager.AppSettings["SkinFile"];
        private string strlocaion = Path.Combine(Application.StartupPath, exceptlocation);
        private void ptEighteen_Click(object sender, EventArgs e)
        {
            FileStream fs1 = new FileStream(strlocaion, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs1);
            sw.WriteLine("SkinFile=1");
            sw.Close();
            fs1.Close();
            try
            {
                string temp = Path.Combine(Application.StartupPath, @"Skin\Eighteen.ssk");
                skinEngine1.SkinFile = temp;
                this.tabControl2.Visible = false;
            }
            catch
            {
                MessageBox.Show("指定的皮肤文件丢失，不能使用!\r\n");
                this.tabControl2.Visible = false;
                return;
            }
        }

        private void ptVista_Click(object sender, EventArgs e)
        {
            FileStream fs1 = new FileStream(strlocaion, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs1);
            sw.WriteLine("SkinFile=2");
            sw.Close();
            fs1.Close();
            try
            {
                string temp = Path.Combine(Application.StartupPath, @"Skin\vista1.ssk");
                skinEngine1.SkinFile = temp;
                this.tabControl2.Visible = false;
            }
            catch
            {
                MessageBox.Show("指定的皮肤文件丢失，不能使用!\r\n");
                this.tabControl2.Visible = false;
                return;
            }
        }

        private void ptSports_Click(object sender, EventArgs e)
        {
            FileStream fs1 = new FileStream(strlocaion, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs1);
            sw.WriteLine("SkinFile=3");
            sw.Close();
            fs1.Close();
            try
            {
                string temp = Path.Combine(Application.StartupPath, @"Skin\SportsBlack.ssk");
                skinEngine1.SkinFile = temp;
                this.tabControl2.Visible = false;
            }
            catch
            {
                MessageBox.Show("指定的皮肤文件丢失，不能使用!\r\n");
                this.tabControl2.Visible = false;
                return;
            }
        }

        private void ptEmerald_Click(object sender, EventArgs e)
        {
            FileStream fs1 = new FileStream(strlocaion, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs1);
            sw.WriteLine("SkinFile=4");
            sw.Close();
            fs1.Close();
            try
            {
                string temp = Path.Combine(Application.StartupPath, @"Skin\Emerald.ssk");
                skinEngine1.SkinFile = temp;
                this.tabControl2.Visible = false;
            }
            catch
            {
                MessageBox.Show("指定的皮肤文件丢失，不能使用!\r\n");
                this.tabControl2.Visible = false;
                return;
            }
        }

        private void panel3_Click(object sender, EventArgs e)
        {
            this.tabControl2.Visible = false;

        }

        private void button7_Click(object sender, EventArgs e)
        {
            this.tabControl2.Visible = false;

        }

        private void groupBox3_MouseCaptureChanged(object sender, EventArgs e)
        {
            this.tabControl2.Visible = false;
        }

        private void groupBox2_MouseCaptureChanged(object sender, EventArgs e)
        {
            this.tabControl2.Visible = false;

        }

        private void groupBox1_MouseCaptureChanged(object sender, EventArgs e)
        {
            this.tabControl2.Visible = false;

        }

        private void groupBox4_MouseCaptureChanged(object sender, EventArgs e)
        {
            this.tabControl2.Visible = false;

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ClearMemory();
        }
        private void SaveAs() //另存新档按钮   导出成Excel
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "Export Excel File To";
            saveFileDialog.ShowDialog();
            Stream myStream;
            
            myStream = saveFileDialog.OpenFile();
            //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string str = "";
            try
            {
                //写标题
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "/n";
                    }
                    str += dataGridView1.Columns[i].HeaderText;
                }
                sw.WriteLine(str);
                //写内容
                for (int j = 0; j < dataGridView1.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGridView1.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "/t";
                        }
                        tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }

        public static bool SaveDataTableToExcel(System.Data.DataTable excelTable, string filePath)
        {
            Microsoft.Office.Interop.Excel.Application app =
            new Microsoft.Office.Interop.Excel.Application();
            try
            {
                app.Visible = false;
                Microsoft.Office.Interop.Excel.Workbook wBook = app.Workbooks.Add(true);
                Microsoft.Office.Interop.Excel.Worksheet wSheet = wBook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
                if (excelTable.Rows.Count > 0)
                {
                    int row = 0;
                    row = excelTable.Rows.Count;
                    int col = excelTable.Columns.Count;
                    for (int i = 0; i < row; i++)
                    {
                        for (int j = 0; j < col; j++)
                        {
                            string str = excelTable.Rows[i][j].ToString();
                            wSheet.Cells[i + 2, j + 1] = str;
                        }
                    }
                }

                int size = excelTable.Columns.Count;
                for (int i = 0; i < size; i++)
                {
                    wSheet.Cells[1, 1 + i] = excelTable.Columns[i].ColumnName;
                }
                //设置禁止弹出保存和覆盖的询问提示框 
                app.DisplayAlerts = true;
                app.AlertBeforeOverwriting = true;
                //保存工作簿 
                wBook.Save();
                //wBook.SaveAs("Sheet1.xlsx", null, null, null, null, null, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null); 
                //保存excel文件
                MessageBox.Show(Application.StartupPath);
                app.Save(Application.StartupPath);
                app.SaveWorkspace(Application.StartupPath);
                app.Quit();
                app = null;
                return true;
            }
            catch (Exception err)
            {
                MessageBox.Show("导出Excel出错！错误原因：" + err.Message, "提示信息",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            finally
            {
            }
        }

        public void printAll(System.Data.DataTable dt)
        {

            //导出到execl 

            try
            {

                SaveFileDialog saveFileDialog = new SaveFileDialog();

                saveFileDialog.Filter = "导出Excel (*.xls)|*.xls";

                saveFileDialog.FilterIndex = 0;

                saveFileDialog.RestoreDirectory = true;

                saveFileDialog.CreatePrompt = true;

                saveFileDialog.Title = "导出文件保存路径";

                saveFileDialog.ShowDialog();

                string strName = saveFileDialog.FileName;

                if (strName.Length != 0)
                {

                    //没有数据的话就不往下执行 

                    if (dt.Rows.Count == 0)

                        return;



                    // toolStripProgressBar1.Visible = true; 

                    System.Reflection.Missing miss = System.Reflection.Missing.Value;

                    //实例化一个Excel.Application对象 

                    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

                    excel.Application.Workbooks.Add(true);

                    excel.Visible = false;//若是true，则在导出的时候会显示EXcel界面。 

                    if (excel == null)
                    {

                        MessageBox.Show("EXCEL无法启动！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        return;

                    }

                    Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;

                    Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));

                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;

                    sheet.Name = "test";

                    int m = 0, n = 0;





                    //生成Excel中列头名称 

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {

                        excel.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;//输出DataGridView列头名 

                    }



                    //把DataGridView当前页的数据保存在Excel中 

                    if (dt.Rows.Count > 0)
                    {

                        for (int i = 0; i < dt.Rows.Count; i++)//控制Excel中行，上下的距离，就是可以到Excel最下的行数，比数据长了报错，比数据短了会显示不完 
                        {

                            for (int j = 0; j < dt.Columns.Count; j++)//控制Excel中列，左右的距离，就是可以到Excel最右的列数，比数据长了报错，比数据短了会显示不完 
                            {

                                string str = dt.Rows[i][j].ToString();

                                excel.Cells[i + 2, j + 1] = "'" + str;//i控制行，从Excel中第2行开始输出第一行数据，j控制列，从Excel中第1列输出第1列数据，"'" +是以string形式保存，所以遇到数字不会转成16进制 

                            }
                        }
                    }
                    sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
                    book.Close(false, miss, miss);
                    books.Close();
                    excel.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
                    GC.Collect();
                    MessageBox.Show("数据已经成功导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // toolStripProgressBar1.Value = 0; 
                    System.Diagnostics.Process.Start(strName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示");
            }

        } 

         public bool DataTableToExcelTow(DataTable dtData)
        {
            SaveFileDialog saveFileDlg = new SaveFileDialog();
            try
            {
                //Select Excel File
                saveFileDlg.InitialDirectory = "c://";
                saveFileDlg.Filter = "Excel files (*.xls)|*.xls";
                saveFileDlg.FilterIndex = 2;
                saveFileDlg.RestoreDirectory = true;
                if (saveFileDlg.ShowDialog() != DialogResult.OK)
                    return false;
                 //Create OleDbConn
                string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;"

                               + "Data Source=" + saveFileDlg.FileName + ";"

                               + "Extended Properties=@/"Excel 5.0;HDR=YES/"";
                OleDbConnection OleDbConn = new OleDbConnection();
                OleDbConn.ConnectionString = connStr;
                OleDbConn.Open();
                OleDbCommand cmd = new OleDbCommand();
                cmd.Connection = OleDbConn;
                //Create Table Of Excel
                string createTableStr = "Create Table [" + dtData.TableName + "](";
                int i, j, k;
                for (i = 0; i < dtData.Columns.Count - 1; i++)
                {
                    createTableStr += "[" + dtData.Columns[i].ColumnName + "] text,";
                }
               createTableStr += dtData.Columns[i].ColumnName + " text)";
                cmd.CommandText = createTableStr;
                cmd.ExecuteNonQuery();
                //Save Data To Excel File
                string insertStr = "";
                for (j = 0; j < gv.RowCount; j++)
                {
                    insertStr = "INSERT INTO [" + dtData.TableName + "] values('";
                    for (k = 0; k < dtData.Columns.Count - 1; k++)
                    {
                        insertStr += dtData.Rows[k].ToString() + "','";
                    }
                    insertStr += dtData.Rows[k].ToString() + "')";
                    cmd.CommandText = insertStr;
                    cmd.ExecuteNonQuery();
                }
                //Close OleDbConn
                OleDbConn.Close();
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message);
            }
            finally
            {
                if (saveFileDlg != null)
                {
                    saveFileDlg.Dispose();
                }
            }
        }



    }
}
